package com.alexb.tasksreport.resource;

import java.util.Collection;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import com.alexb.tasksreport.model.Person;
import com.alexb.tasksreport.util.PMF;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@Path("/persons")
public class PersonsResource {

    @GET
    @Produces("application/json")
    public Collection<Person> list() {
    	
    	UserService userService = UserServiceFactory.getUserService();
    	String userId = userService.getCurrentUser().getUserId();
    	
    	Collection<Person> allPersons;

    	PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
        	Query query = pm.newQuery(Person.class);
        	query.setFilter("managerId == userId");
        	query.declareParameters("String userId");
        	allPersons = pm.detachCopyAll((Collection<Person>) query.execute(userId));
        } finally {
            pm.close();
        }

        return allPersons;
    }

    @POST
    @Produces("application/json")
    public Person add(@FormParam("id") Long id, @FormParam("firstName") String firstName, @FormParam("lastName") String lastName) {
    	
    	UserService userService = UserServiceFactory.getUserService();
    	String userId = userService.getCurrentUser().getUserId();
    	
    	Person person = new Person();
    	person.setId(id);
    	person.setManagerId(userId);
    	person.setFirstName(firstName);
    	person.setLastName(lastName);
    	
    	PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
        	pm.makePersistent(person);
        } finally {
            pm.close();
        }

        return person;
    }
}
